package org.exam.system.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.exam.exception.BusinessException;
import org.exam.system.domain.Logininfo;
import org.exam.system.domain.Menu;
import org.exam.system.domain.Role;
import org.exam.system.dto.LoginDto;
import org.exam.system.jwt.JwtUtil;
import org.exam.system.jwt.Payload;
import org.exam.system.mapper.LogininfoMapper;
import org.exam.system.query.LogininfoQuery;
import org.exam.system.service.ILogininfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public class LogininfoServiceImpl implements ILogininfoService {
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    @Transactional
    public void add(Logininfo logininfo) {
        logininfoMapper.add(logininfo);
    }

    @Override
    @Transactional
    public void delete(Long id) {
        logininfoMapper.delete(id);
        //条件删除
    }

    @Override
    public Logininfo get(Long id) {
        return logininfoMapper.get(id);
    }

    @Override
    public List<Logininfo> getAll() {
        return logininfoMapper.getAll();
    }

    @Override
    @Transactional
    public void update(Logininfo logininfo) {
        logininfoMapper.update(logininfo);
    }

    @Override
    public void patchDelete(Long[] ids) {
        logininfoMapper.patchDelete(ids);
    }

    @Override
//    分页
    public PageInfo<Logininfo> queryPage(LogininfoQuery logininfoQuery) {
        PageHelper.startPage(logininfoQuery.getCurrentPage(), logininfoQuery.getPageSize());
        List<Logininfo> data = logininfoMapper.queryPage(logininfoQuery);
//===========================================================================================================

        return new PageInfo<>(data);
    }

    @Override
    public String accountLogin(LoginDto loginDto) {
//        接受账号和密码还有类型
        String account = loginDto.getAccount();
        String password = loginDto.getPassword();
        Integer type = loginDto.getType();
//        判断账号和密码是否为空
        if (StrUtil.isBlank(account) || StrUtil.isBlank(password)) {
            throw new BusinessException("参数不能为空");
        }
//                        获取得到的对应账号和类型的对象
        Logininfo logininfo = logininfoMapper.findByAccount(loginDto);
//        判断账号是否存在
        if (logininfo == null) {
            throw new BusinessException("账号不存在");
        }
//        将我们传入的密码和定义好的盐值进行一个添加并且加密
        String s = SecureUtil.md5(password + logininfo.getSalt());
//        看加密后的密码和logininfo对象的密码是否相同
        if (!s.equals(logininfo.getPassword())) {
            throw new BusinessException("密码错误");
        }
//        判断状态:是否还可用
        if (!logininfo.getDisable()) {
            throw new BusinessException("次账号被禁用");
        }
//        我们定义了一个类来存储我们所需要的Logininfo类....的数据
//        创建一个对象来尽心存储
        Payload payload = new Payload();
        logininfo.setSalt(null);
        logininfo.setPassword(null);
        payload.setLogininfo(logininfo);
//        判断是用户还是管理员,角色不同看到的菜单不一样
        if (logininfo.getType() == 0) {
            List<String> permissions = logininfoMapper.findPermissionByLogininfoId(logininfo);
            List<Menu> menus = menuTree4LogininfoId(logininfo.getId());
            payload.setPermissions(permissions);
            payload.setMenus(menus);

        }
        String s1 = JwtUtil.generateToken(payload);
        return s1;


    }

    private List<Menu> menuTree4LogininfoId(Long logininfoId) {
//        查询当前员工的所有菜单信息
        List<Menu> menus = logininfoMapper.findMenuByLogininfoId(logininfoId);
        List<Menu> menuTree = new ArrayList<>();
        //作用:方便通过id获取对象
        Map<Long, Menu> map = new HashMap<>();
        for (Menu menu : menus) {
            map.put(menu.getId(), menu);
        }
        for (Menu menu : menus) {
            if (menu.getParentId() == null) {
                menuTree.add(menu);
            } else {
                Long parentId = menu.getParentId();
                Menu parentMenu = map.get(parentId);
                if (parentMenu != null) {
                    parentMenu.getChildren().add(menu);
                }
            }
        }
        return menuTree;
    }

    public static void main(String[] args) {
        String salt1 = RandomUtil.randomString(32);
        String salt2 = RandomUtil.randomString(32);
        System.out.println(salt1);
        //28hgksjpbhjm8qb18gtfghhau5mff9y8
        System.out.println(salt2);
        //h7t9jjon4ngm34rhc4w7mafvg2mguvof
        String pw1 = "123456";
        String md5pw1 = SecureUtil.md5(pw1 + salt1);
        System.out.println(md5pw1);
        //d2a58db4570ebdab8371f4f20aba8f5a
        String pw2 = "123456";
        String md5pw2 = SecureUtil.md5(pw2 + salt2);
        System.out.println(md5pw2);
        //3cc791301b2027275a34ca1e4c3cafbd

    }

}
